package day11;

public class CircleSqQueue<T> implements IQueue<T>{

        private T[] queueElem;
        private int front;
        private int rear;
        private int maxSize;

        public CircleSqQueue(int maxSize) {
            front = rear = 0;
            queueElem = (T[]) new Object[maxSize];
            this.maxSize = maxSize;
        }

        @Override
        public void clear() {
            front = rear = 0;
        }

        @Override
        public boolean isEmpty() {
            return rear == front;
        }

        @Override
        public int length() {
            return (rear-front+maxSize)%maxSize;
        }

        @Override
        public T peek() {
            if (isEmpty()){
                return null;
            }
            return queueElem[front];
        }

        @Override
        public void offer(T x) throws Exception {
            if ((rear + 1) % maxSize == maxSize){
                throw new Exception("队列已满");
            }
            queueElem[rear] = x;
            rear = (rear + 1) % maxSize;
        }

        @Override
        public T poll() {
            if (rear == front)
                return null;
            T p = queueElem[front];
            front = (front + 1) % maxSize;
            return p;
        }

        @Override
        public void display() {
            System.out.println("列队中元素如下");
            if (!isEmpty()){
                if (front < rear){
                    for (int i = front;i < rear;i++){
                        System.out.println(queueElem[i] + " ");
                    }
                }else {
                    for (int i = front;i <maxSize;i++){
                        System.out.println(queueElem[i] + " ");
                    }
                    for (int i = 0;i < rear;i++){
                        System.out.println(queueElem[i] + " ");
                    }
                }
            }
            else {
                System.out.println("此队列为空");
            }
        }

}
